package com.online_video.servlet.client;

import com.google.gson.Gson;
import com.online_video.entity.User;
import com.online_video.service.UserService;
import com.online_video.service.impl.UserServiceImpl;
import com.online_video.servlet.BaseServlet;
import com.online_video.utils.GetMD5;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zhenghouwen
 * @create 2022-03-14 14:15
 */
@WebServlet("/client/user.do")
@MultipartConfig(location = "D:/img/", fileSizeThreshold = 1024 * 1024 * 5, maxFileSize = 1024 * 1024 * 5 * 5, maxRequestSize = -1)
public class UserServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();

    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Cookie usernameCookie;
        Cookie passwordCookie;
        String username = request.getParameter("username");
        String remeberMe = request.getParameter("remeberMe");
        String password = "";
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if ("password".equals(cookie.getName())) {
                password = cookie.getValue();
                break;
            } else {
                password = GetMD5.string2MD5(request.getParameter("password"));
            }
        }
        if (request.getParameter("username").equals("admin")){
            request.getRequestDispatcher("../admin/index.jsp").forward(request,response);

    }else {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);

            User login = userService.login(user);
            //登录成功
            if (login != null) {
                //该账户状态是否激活
                if (login.getIsactive() == 1) {
                    //记住我
                    if ("remember-me".equals(remeberMe)) {
                        usernameCookie = new Cookie("username", username);
                        passwordCookie = new Cookie("password", password);
                        usernameCookie.setMaxAge(60 * 60 * 24 * 7);
                        passwordCookie.setMaxAge(60 * 60 * 24 * 7);
                        response.addCookie(usernameCookie);
                        response.addCookie(passwordCookie);

                        HttpSession session = request.getSession();
                        session.setMaxInactiveInterval(60 * 60 * 24);
                        session.setAttribute("user", login);
                        request.getRequestDispatcher("./index.jsp").forward(request, response);

                    } else {
                        usernameCookie = new Cookie("username", username);
                        passwordCookie = new Cookie("password", password);
                        usernameCookie.setMaxAge(0);
                        passwordCookie.setMaxAge(0);
                        response.addCookie(usernameCookie);
                        response.addCookie(passwordCookie);

                        HttpSession session = request.getSession();
                        response.sendRedirect("./index.jsp");
                    }
                } else {
                    request.setAttribute("code", "666");
                    request.getRequestDispatcher("./login.jsp").forward(request, response);
                }

            } else {
                //登录失败
                request.setAttribute("code", "-1");
                request.getRequestDispatcher("./login.jsp").forward(request, response);
            }
        }



    }

    public void isExistsUsername(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        boolean existsUsername = userService.isExistsUsername(username);
        if (existsUsername) {
            Gson gson = new Gson();
            String jsonStr = gson.toJson("用户名已存在");
            PrintWriter writer = response.getWriter();
            writer.write(jsonStr);
        }
    }

    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = GetMD5.string2MD5(request.getParameter("password"));
        String nickname = request.getParameter("nickname");
        String telephone = request.getParameter("telephone");
        String email = request.getParameter("email");
        String sex = request.getParameter("gender");

        User user = new User(null, 1, username, password, nickname, sex, telephone, email, null, null, 1, 0);
        int register = userService.register(user);
        if (register > 0) {

            Cookie usernameCookie;
            Cookie passwordCookie;
            usernameCookie = new Cookie("username", username);
            passwordCookie = new Cookie("password", password);
            usernameCookie.setMaxAge(60 * 60 * 24 * 7);
            passwordCookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(usernameCookie);
            response.addCookie(passwordCookie);

            User login = userService.login(user);
            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(60 * 60 * 24);
            session.setAttribute("user", login);


            Gson gson = new Gson();
            String str = "注册成功";
            String jsonStr = gson.toJson(str);
            response.getWriter().write(jsonStr);
        }
    }

    public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession(false).invalidate();
        request.getRequestDispatcher("./index.jsp").forward(request, response);
    }


    public void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User) request.getSession(false).getAttribute("user");
        String headportrait = request.getParameter("fakeheadportrait");
        String nickname = request.getParameter("nickname");
        String telephone = request.getParameter("telephone");
        String email = request.getParameter("email");
        user.setHeadportrait(headportrait);
        user.setNickname(nickname);
        user.setTelephone(telephone);
        user.setEmail(email);
        int result = userService.update(user);
        if (result > 0) {
            response.getWriter().write("成功");
        } else {
            response.getWriter().write("失败");
        }

    }


    public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        PrintWriter writer = response.getWriter();

        Part part = request.getPart("file");
        //获取文件后缀名，即文件类型
        String realFileName = part.getSubmittedFileName();//获取文件名
        String type = realFileName.substring(realFileName.lastIndexOf("."));//获取文件类型

        //通过UUID 生成随机文件名
        String fileName = UUID.randomUUID().toString() + type;
        System.out.println();
        //获取项目下的该文件夹路径，必须先创建文件夹
        String path = "../../img/" + fileName;

        part.write(path);
        //将文件名信息回传至前端
        writer.write(fileName);
        System.out.println();
    }

    public void checkPrePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        String beforePwd = GetMD5.string2MD5(request.getParameter("beforePwd"));
        User user1 = userService.queryByU_id(user.getId());
        if (!beforePwd.equals(user1.getPassword())) {
            response.getWriter().print(-1);
        } else {
            response.getWriter().print(1);
        }
    }

    public void updatePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        String pwd = GetMD5.string2MD5(request.getParameter("password"));
        int i = userService.updatePwd(pwd, user.getId());
        response.getWriter().print(i);
    }

    public void queryByU_Id(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer u_id = Integer.parseInt(request.getParameter("u_id"));
        User user = userService.queryByU_id(u_id);
        if (user != null) {
            Gson gson = new Gson();
            String toJson = gson.toJson(user);
            response.getWriter().write(toJson);
        }
    }
}
